package cn.edu.sdjzu.xg.eagle.dao.mapper;

import cn.edu.sdjzu.xg.eagle.dao.OrganizationDaoInterface;
import cn.edu.sdjzu.xg.eagle.entity.Organization;
import cn.edu.sdjzu.xg.eagle.util.JdbcPoolUtil;
import com.alibaba.fastjson2.JSON;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

public class OrganizationDaoImpl implements OrganizationDaoInterface {

    @Override
    public void save( Connection conn,Organization organization) {
        String sql = "INSERT INTO Organization (name, no, remarks, parent_id) VALUES (?,?,?,?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, organization.getName());
            pstmt.setString(2, organization.getNo());
            pstmt.setString(3, organization.getRemarks());
            if (organization.getParent() != null) {
                pstmt.setLong(4, organization.getParent().getId());
            } else {
                pstmt.setNull(4, java.sql.Types.BIGINT);
            }
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Organization findById(Connection conn, Long id) {
        String sql = "SELECT * FROM Organization WHERE id = ?";
        Organization organization = null;
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                organization = new Organization();
                organization.setId(rs.getLong("id"));
                organization.setName(rs.getString("name"));
                organization.setNo(rs.getString("no"));
                organization.setRemarks(rs.getString("remarks"));
                Long parentId = rs.getLong("parent_id");
                if (!rs.wasNull()) {
                    organization.setParent(findById(conn, parentId));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organization;
    }

    @Override
    public void update(Connection conn, Organization organization) {
        String sql = "UPDATE Organization SET name = ?, no = ?, remarks = ?, parent_id = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, organization.getName());
            pstmt.setString(2, organization.getNo());
            pstmt.setString(3, organization.getRemarks());
            if (organization.getParent() != null) {
                pstmt.setLong(4, organization.getParent().getId());
            } else {
                pstmt.setNull(4, java.sql.Types.BIGINT);
            }
            pstmt.setLong(5, organization.getId());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Connection conn, Long id) {
        String sql = "DELETE FROM Organization WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Collection<Organization> findAll(Connection conn) {
        String sql = "SELECT * FROM Organization";
        Collection<Organization> organizations = new ArrayList<>();
        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                Organization organization = new Organization();
                organization.setId(rs.getLong("id"));
                organization.setName(rs.getString("name"));
                organization.setNo(rs.getString("no"));
                organization.setRemarks(rs.getString("remarks"));
                Long parentId = rs.getLong("parent_id");
                if (!rs.wasNull()) {
                    organization.setParent(findById(conn, parentId));
                }
                organizations.add(organization);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organizations;
    }

    /**
     * 递归查询某个id对应的Organization的所有子对象（但不包含对象本身）
     * @param conn 数据库连接
     * @param parentId 父级组织的id
     * @return 返回树形结构的Organization对象列表     */

    public Collection<Organization> findAllChildren(Connection conn, Long parentId) {
        String sql = "SELECT * FROM Organization WHERE parent_id = ?";
        Collection<Organization> organizations = new ArrayList<>();
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, parentId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Organization organization = new Organization();
                    organization.setId(rs.getLong("id"));
                    organization.setName(rs.getString("name"));
                    organization.setNo(rs.getString("no"));
                    organization.setRemarks(rs.getString("remarks"));
                    organization.setChildren(findAllChildren(conn, organization.getId())); // 递归查询子级对象
                    organizations.add(organization);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organizations;
    }

    /**
     * 递归查询某个id对应的Organization对象及其所有子对象
     * @param conn 数据库连接
     * @param parentId 父级组织的id
     * @return 返回树形结构的Organization对象列表
     */
    public Collection<Organization> findWithAllChildren(Connection conn, Long parentId) {
        Collection<Organization> organizations = new ArrayList<>();

        // 先获取当前组织对象本身
        Organization parentOrganization = findById(conn, parentId);
        if (parentOrganization != null) {
            // 递归查询子级对象
            parentOrganization.setChildren(findChildren(conn, parentId));
            organizations.add(parentOrganization);
        }

        return organizations;
    }

    /**
     * 递归查询某个id对应的Organization对象的所有子对象
     * @param conn 数据库连接
     * @param parentId 父级组织的id
     * @return 返回树形结构的Organization对象列表
     */
    private Collection<Organization> findChildren(Connection conn, Long parentId) {
        String sql = "SELECT * FROM Organization WHERE parent_id = ?";
        Collection<Organization> children = new ArrayList<>();
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, parentId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Organization organization = new Organization();
                    organization.setId(rs.getLong("id"));
                    organization.setName(rs.getString("name"));
                    organization.setNo(rs.getString("no"));
                    organization.setRemarks(rs.getString("remarks"));
                    // 递归查询子级对象
                    organization.setChildren(findChildren(conn, organization.getId()));
                    children.add(organization);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return children;
    }

    public static void main(String[] args) {
        // 创建OrganizationDaoImpl实例
        OrganizationDaoImpl organizationDao = new OrganizationDaoImpl();

        // 获取数据库连接
        Connection conn = null;
        try {
            conn = JdbcPoolUtil.getConn(); // 假设你有一个JdbcPoolUtil工具类来获取数据库连接
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("无法获取数据库连接");
            return;
        }

        // 调用findTreeStructure方法，查询某个id对应的组织及其所有子对象
        Long parentId = 2L; // 假设要查询的父级组织的id为1
        Collection<Organization> treeStructure = null;
        try {
            treeStructure = organizationDao.findWithAllChildren(conn, parentId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询树形结构时出错");
        }

        // 打印树形结构的JSON字符串
        if (treeStructure != null) {
            String jsonString = JSON.toJSONString(treeStructure);
            System.out.println("树形结构的JSON字符串：");
            System.out.println(jsonString);
        } else {
            System.out.println("未找到任何组织数据");
        }

        // 关闭数据库连接
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}